"""Swagger 文档模块

负责离线 Swagger 文档的配置和管理。
"""

import os
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from config.config_manager import get_swagger_config


def add_offline_swagger_docs(app: FastAPI):
    """添加离线 Swagger 文档支持 - 强制使用本地文件
    
    Args:
        app: FastAPI 应用实例
    """
    # 获取 Swagger 配置
    swagger_config = get_swagger_config()

    # 配置离线 Swagger UI - 直接使用本地文件
    @app.get("/docs", include_in_schema=False)
    async def custom_swagger_ui_html():
        js_url = f"/static/{swagger_config['local_js_file']}"
        css_url = f"/static/{swagger_config['local_css_file']}"
        favicon_url = f"/static/{swagger_config['local_favicon_file']}"
        print(f"离线模式URLs: js={js_url}, css={css_url}, favicon={favicon_url}")
        return get_swagger_ui_html(
            openapi_url="/openapi.json",
            title=app.title + " - Swagger UI (离线版)",
            swagger_js_url=js_url,
            swagger_css_url=css_url,
            swagger_favicon_url=favicon_url
        )


def generate_openapi_schema(app: FastAPI):
    """生成 OpenAPI 规范
    
    Args:
        app: FastAPI 应用实例
        
    Returns:
        dict: OpenAPI 规范字典
    """
    if app.openapi_schema:
        return app.openapi_schema
        
    openapi_schema = get_openapi(
        title=app.title,
        version=app.version,
        description=app.description,
        routes=app.routes,
    )
    app.openapi_schema = openapi_schema
    return openapi_schema
